package com.gexiaobao.pigeon.app

import android.app.NotificationChannel
import android.app.NotificationChannelGroup
import android.app.NotificationManager
import android.content.Context
import android.content.IntentFilter
import android.graphics.Color
import android.net.ConnectivityManager
import android.os.Build
import androidx.multidex.MultiDex
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.alibaba.ha.adapter.AliHaAdapter
import com.alibaba.ha.adapter.AliHaConfig
import com.alibaba.ha.adapter.Plugin
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.alibaba.sdk.android.push.notification.AdvancedCustomPushNotification
import com.alibaba.sdk.android.push.notification.CustomNotificationBuilder
import com.alivc.live.baselive_push.ui.LivePushActivity.ConnectivityChangedReceiver
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.event.AppViewModel
import com.gexiaobao.pigeon.app.event.EventViewModel
import com.gexiaobao.pigeon.app.ext.loadcallback.EmptyCallback
import com.gexiaobao.pigeon.app.ext.loadcallback.ErrorCallback
import com.gexiaobao.pigeon.app.ext.loadcallback.LoadingCallback
import com.gexiaobao.pigeon.app.model.bean.MyObjectBox
import com.gexiaobao.pigeon.ui.activity.ErrorActivity
import com.gexiaobao.pigeon.ui.activity.WelcomeActivity
import com.google.android.material.internal.ContextUtils
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadSir
import com.tencent.mmkv.MMKV
import io.objectbox.BoxStore
import me.hgj.jetpackmvvm.base.BaseApp
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.ext.util.jetpackMvvmLog
import me.hgj.jetpackmvvm.util.LogUtils
import kotlin.system.exitProcess


/**
 * @Author      : hxw
 * @Date        : 2023/5/31 8:44
 * @Describe    :
 */

//Application全局的ViewModel，里面存放了一些账户信息，基本配置信息等
val appViewModel: AppViewModel by lazy { App.appViewModelInstance }

//Application全局的ViewModel，用于发送全局通知操作
val eventViewModel: EventViewModel by lazy { App.eventViewModelInstance }

class App : BaseApp() {

    var deviceId: String = ""

    companion object {
        lateinit var instance: App
        lateinit var eventViewModelInstance: EventViewModel
        lateinit var appViewModelInstance: AppViewModel

        var isFirstAccountCheck = true //用于"我的账户" 一次登录提示相关信息

        //数据库
        var boxStore: BoxStore? = null

        fun exitAll() {
            KtxActivityManger.finishAllActivity()
            exitProcess(0)
        }
    }

    override fun onCreate() {
        super.onCreate()
        MMKV.initialize(this.filesDir.absolutePath + "/mmkv")
        instance = this
        eventViewModelInstance = getAppViewModelProvider()[EventViewModel::class.java]
        appViewModelInstance = getAppViewModelProvider()[AppViewModel::class.java]
        MultiDex.install(this)
        //界面加载管理 初始化
        LoadSir.beginBuilder()
            .addCallback(LoadingCallback())//加载
            .addCallback(ErrorCallback())//错误
            .addCallback(EmptyCallback())//空
            .setDefaultCallback(SuccessCallback::class.java)//设置默认加载状态页
            .commit()
        jetpackMvvmLog = true
        //初始化防崩溃
        initCaocConfig()
        initObjectBox()
        PushServiceFactory.init(this)
        /** 初始化阿里云消息推送 */
        initCloudChannel(instance)
//        PushLaunchManager.launch4All(this)

        val filter = IntentFilter()
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(ConnectivityChangedReceiver(), filter)
//        PushLaunchManager.launch4All(this)
    }

    private fun initObjectBox() {
        //MyObjectBox找不到，必须先创建一个对象，然后重新编译，才可以
        boxStore = MyObjectBox.builder().androidContext(this).build()
    }

    private fun initCaocConfig() {
        //当 App 中出现多进程, 并且您需要适配所有的进程, 就需要在 App 初始化时调用 initCompatMultiProcess()
        //在 Demo 中跳转的三方库中的 DefaultErrorActivity 就是在另外一个进程中, 所以要想适配这个 Activity 就需要调用 initCompatMultiProcess()
        //AutoSize.initCompatMultiProcess(this)
        //防止项目崩溃，崩溃后打开错误界面
        CaocConfig.Builder.create()
            .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM
            .enabled(true)//是否启用CustomActivityOnCrash崩溃拦截机制 必须启用！不然集成这个库干啥？？？
            .showErrorDetails(true) //是否必须显示包含错误详细信息的按钮 default: true
            .showRestartButton(false) //是否必须显示“重新启动应用程序”按钮或“关闭应用程序”按钮default: true
            .logErrorOnRestart(true) //是否必须重新堆栈堆栈跟踪 default: true
            .trackActivities(true) //是否必须跟踪用户访问的活动及其生命周期调用 default: false
            .minTimeBetweenCrashesMs(2000) //应用程序崩溃之间必须经过的时间 default: 3000
            .restartActivity(WelcomeActivity::class.java) // 重启的activity
            .errorActivity(ErrorActivity::class.java) //发生错误跳转的activity
            .apply()
    }

    private fun initHa() {
        val config = AliHaConfig()
        config.appKey = "333827899"
        config.appVersion = "2.0.4"
        config.appSecret = "72c1e171648b45de87e0ddd64e9741f1"
        config.channel = "pigeon_android"
        config.userNick = null
        config.application = this
        config.context = applicationContext
        config.isAliyunos = false
        //启动CrashReporter
        AliHaAdapter.getInstance().addPlugin(Plugin.crashreporter)
        AliHaAdapter.getInstance().start(config)
    }

    /**
     * 设置基础自定义样式通知示例
     * 1. 详细API介绍请参考:https://help.aliyun.com/document_detail/30066.html#h3-3-4-basiccustompushnotification-api
     */
    private fun setBasicCusNotification() {
        val notification =
            AdvancedCustomPushNotification(
                R.layout.notification_cus_notif,
                R.id.m_icon,
                R.id.m_title,
                R.id.m_text
            ) //创建高级自定义样式通知,设置布局文件以及对应的控件ID
        notification.icon = R.mipmap.app_icon_
        notification.isServerOptionFirst = true //设置服务端配置优先
        notification.isBuildWhenAppInForeground = false //设置当推送到达时如果应用处于前台不创建通知
        CustomNotificationBuilder.getInstance()
            .setCustomNotification(1, notification) //注册该通知,并设置ID为2
    }

    /**
     * 初始化云推送通道
     * @param applicationContext
     */
    private fun initCloudChannel(applicationContext: Context) {
        /** 创建Notification channel */
        this.createNotificationChannel()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val group = NotificationChannelGroup("pigeonGroup", "pigeonChannelGroup")
            notificationManager.createNotificationChannelGroup(group)

            val channel = NotificationChannel(
                "pigeon_treasure",
                "pigeonChannel",
                NotificationManager.IMPORTANCE_HIGH
            )
            channel.description = "PigeonTreasure Notification Description"
            channel.enableLights(true)
            channel.lightColor = Color.RED
            channel.enableVibration(true)
            channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
//            channel.setSound(
//                Uri.parse("android.resource://" + packageName + "/" + R.raw.alicloud_notification_sound),
//                Notification.AUDIO_ATTRIBUTES_DEFAULT
//            )
            channel.group = "pigeonGroup"
            notificationManager.createNotificationChannel(channel)
        }
        val pushService = PushServiceFactory.getCloudPushService()
        //pushService.setLogLevel(CloudPushService.LOG_DEBUG) //仅适用于Debug包，正式包不需要此行
        pushService.register(applicationContext, object : CommonCallback {
            override fun onSuccess(response: String?) {
                LogUtils.debugInfo("init cloudChannel success")
                deviceId = pushService.deviceId
            }

            override fun onFailed(errorCode: String, errorMessage: String) {
                LogUtils.debugInfo("init cloudChannel failed -- errorCode:$errorCode -- errorMessage:$errorMessage")
            }
        })
    }
//    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mNotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            // 通知渠道的id
            val id = "1"
            // 用户可以看到的通知渠道的名字.
            val name: CharSequence = "notification channel"
            // 用户可以看到的通知渠道的描述
            val description = "notification description"
            val importance = NotificationManager.IMPORTANCE_HIGH
            val mChannel = NotificationChannel(id, name, importance)
            // 配置通知渠道的属性
            mChannel.description = description
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true)
            mChannel.lightColor = Color.RED
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true)
            mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            //最后在notificationManager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel)
        }
    }

}